package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Component
        //0.认证管理器对该Service进行管理
public class SpringSecurityUserService implements UserDetailsService {
    @Reference
     UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.查询数据库，获取pojo：User
        User user = userService.findUserByName(username);
        if(user==null){
            return null;
        }
        //2.为该用户动态授权
        //这里设置的角色和权限，将配合SpringSecurity.xml中的
        List<GrantedAuthority> authoritList = new ArrayList<>();
        Set<Role> roleSet = user.getRoles();
        for (Role role : roleSet) {
            //遍历角色，为用户授权角色
            authoritList.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                //为用户授权权限
                authoritList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        //3.返回一个带有姓名，密码以及拥有角色和权限的user给框架进行验证
        org.springframework.security.core.userdetails.User securityUser =
                new org.springframework.security.core.userdetails.User(username,user.getPassword(),authoritList);
        return securityUser;

    }
}
